package org.mat.ipaas.ucenter.service.modules.system.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.system.query.QueryGenerator;
import org.mat.ipaas.ucenter.biz.common.util.FillRuleUtil;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysFillRule;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysFillRuleService;
import org.mat.ipaas.ucenter.service.api.system.SysFillRuleRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysFillRuleDTO;
import org.mat.ipaas.ucenter.service.modules.MatController;
import org.mat.ipaas.ucenter.service.modules.aop.AutoLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * 填值规则
 */
@Slf4j
@Api(tags = "填值规则")
@RestController
@RequestMapping("/sys/fillRule")
public class SysFillRuleController extends MatController<SysFillRule, ISysFillRuleService> implements SysFillRuleRestAPI {

    @Autowired
    private ISysFillRuleService sysFillRuleService;

    /**
     * 分页列表查询
     *
     * @param sysFillRuleDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "填值规则-分页列表查询")
    @ApiOperation(value = "填值规则-分页列表查询", notes = "填值规则-分页列表查询")
    @GetMapping(value = "/list")
    public MatApiResponse<?> queryPageList(@SpringQueryMap SysFillRuleDTO sysFillRuleDTO,
                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        SysFillRule sysFillRule = toSysFillRule(sysFillRuleDTO);

        QueryWrapper<SysFillRule> queryWrapper = QueryGenerator.initQueryWrapper(sysFillRule, req.getParameterMap());
        Page<SysFillRule> page = new Page<>(pageNo, pageSize);
        IPage<SysFillRule> pageList = sysFillRuleService.page(page, queryWrapper);
        return MatApiResponse.success(pageList);
    }

    /**
     * 测试 ruleCode
     *
     * @param ruleCode
     * @return
     */
    @GetMapping(value = "/testFillRule")
    public MatApiResponse testFillRule(@RequestParam("ruleCode") String ruleCode) {
        Object result = FillRuleUtil.executeRule(ruleCode, new JSONObject());
        return MatApiResponse.success(result);
    }

    /**
     * 添加
     *
     * @param sysFillRuleDTO
     * @return
     */
    @AutoLog(value = "填值规则-添加")
    @ApiOperation(value = "填值规则-添加", notes = "填值规则-添加")
    @PostMapping(value = "/add")
    public MatApiResponse<?> add(@RequestBody SysFillRuleDTO sysFillRuleDTO) {
        SysFillRule sysFillRule = toSysFillRule(sysFillRuleDTO);

        sysFillRuleService.save(sysFillRule);
        return MatApiResponse.success("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sysFillRuleDTO
     * @return
     */
    @AutoLog(value = "填值规则-编辑")
    @ApiOperation(value = "填值规则-编辑", notes = "填值规则-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public MatApiResponse<?> edit(@RequestBody SysFillRuleDTO sysFillRuleDTO) {
        SysFillRule sysFillRule = toSysFillRule(sysFillRuleDTO);

        sysFillRuleService.updateById(sysFillRule);
        return MatApiResponse.success("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "填值规则-通过id删除")
    @ApiOperation(value = "填值规则-通过id删除", notes = "填值规则-通过id删除")
    @DeleteMapping(value = "/delete")
    public MatApiResponse<?> delete(@RequestParam(name = "id", required = true) String id) {
        sysFillRuleService.removeById(id);
        return MatApiResponse.success("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "填值规则-批量删除")
    @ApiOperation(value = "填值规则-批量删除", notes = "填值规则-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public MatApiResponse<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.sysFillRuleService.removeByIds(Arrays.asList(ids.split(",")));
        return MatApiResponse.success("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "填值规则-通过id查询")
    @ApiOperation(value = "填值规则-通过id查询", notes = "填值规则-通过id查询")
    @GetMapping(value = "/queryById")
    public MatApiResponse<?> queryById(@RequestParam(name = "id", required = true) String id) {
        SysFillRule sysFillRule = sysFillRuleService.getById(id);
        return MatApiResponse.success(sysFillRule);
    }

    /**
     * 导出excel
     *
     * @param sysFillRuleDTO
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SysFillRuleDTO sysFillRuleDTO) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        SysFillRule sysFillRule = toSysFillRule(sysFillRuleDTO);

        return super.exportXls(request, sysFillRule, SysFillRule.class, "填值规则");
    }

    /**
     * 通过excel导入数据
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public MatApiResponse<?> importExcel() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();

        return super.importExcel(request, response, SysFillRule.class);
    }

    /**
     * 通过 ruleCode 执行自定义填值规则
     *
     * @param ruleCode 要执行的填值规则编码
     * @param formData 表单数据，可根据表单数据的不同生成不同的填值结果
     * @return 运行后的结果
     */
    @PutMapping("/executeRuleByCode/{ruleCode}")
    public MatApiResponse executeByRuleCode(@PathVariable("ruleCode") String ruleCode, @RequestBody JSONObject formData) {
        Object result = FillRuleUtil.executeRule(ruleCode, formData);
        return MatApiResponse.success(result);
    }


    /**
     * 批量通过 ruleCode 执行自定义填值规则
     *
     * @param ruleData 要执行的填值规则JSON数组：
     *                 示例： { "commonFormData": {}, rules: [ { "ruleCode": "xxx", "formData": null } ] }
     * @return 运行后的结果，返回示例： [{"ruleCode": "order_num_rule", "result": "CN2019111117212984"}]
     */
    @PutMapping("/executeRuleByCodeBatch")
    public MatApiResponse executeByRuleCodeBatch(@RequestBody JSONObject ruleData) {
        JSONObject commonFormData = ruleData.getJSONObject("commonFormData");
        JSONArray rules = ruleData.getJSONArray("rules");
        // 遍历 rules ，批量执行规则
        JSONArray results = new JSONArray(rules.size());
        for (int i = 0; i < rules.size(); i++) {
            JSONObject rule = rules.getJSONObject(i);
            String ruleCode = rule.getString("ruleCode");
            JSONObject formData = rule.getJSONObject("formData");
            // 如果没有传递 formData，就用common的
            if (formData == null) {
                formData = commonFormData;
            }
            // 执行填值规则
            Object result = FillRuleUtil.executeRule(ruleCode, formData);
            JSONObject obj = new JSONObject(rules.size());
            obj.put("ruleCode", ruleCode);
            obj.put("result", result);
            results.add(obj);
        }
        return MatApiResponse.success(results);
    }


    private SysFillRule toSysFillRule(SysFillRuleDTO sysFillRuleDTO) {
        if (sysFillRuleDTO == null) {
            return null;
        }
        SysFillRule sysFillRule = new SysFillRule();
        sysFillRule.setId(sysFillRuleDTO.getId());
        sysFillRule.setRuleName(sysFillRuleDTO.getRuleName());
        sysFillRule.setRuleCode(sysFillRuleDTO.getRuleCode());
        sysFillRule.setRuleClass(sysFillRuleDTO.getRuleClass());
        sysFillRule.setRuleParams(sysFillRuleDTO.getRuleParams());
        sysFillRule.setUpdateBy(sysFillRuleDTO.getUpdateBy());
        sysFillRule.setUpdateTime(sysFillRuleDTO.getUpdateTime());
        sysFillRule.setCreateBy(sysFillRuleDTO.getCreateBy());
        sysFillRule.setCreateTime(sysFillRuleDTO.getCreateTime());
        return sysFillRule;
    }
}